package com.example.hao.broadcastreceiver_service;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;


/**
 * Activity 与 Service 的交互
 *
 * BroadcastReceiver   (原始交互方式一)
 * 使用 BindService      (原始的交互方式二)
 * 使用 Application 全部对象 (不要用)
 * RxJava 响应式编程
 * EventBus /MessageBus 事件巴士 (第三方Api  推荐)
 *
 */

public class MainActivity extends AppCompatActivity {

    private ServiceConnection serviceConnection;
    private String TAG = MainActivity.class.getSimpleName();
    private MainActivity.MusicProgressBroadcastReceiver MusicProgressBroadcastReceiver;
    private TextView tv_show;
    private SeekBar sb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sb = findViewById(R.id.sb);
        tv_show = findViewById(R.id.tv_show);
        MusicProgressBroadcastReceiver = new MusicProgressBroadcastReceiver();
        registerReceiver(MusicProgressBroadcastReceiver, new IntentFilter("x.y.z.progress"));
    }


    public void unBind(View view) {

    }

    public void bind(View view) {

    }

    public void stop(View view) {
        Intent intent = new Intent(this, MyService.class);
        stopService(intent);
    }

    public void start(View view) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (MusicProgressBroadcastReceiver != null) {
            unregisterReceiver(MusicProgressBroadcastReceiver);
        }
    }


    public void play(View view) {
        /**
         * 发送广播给 服务内的广播接收者
         */
        Intent intent = new Intent("a.b.c.music");
        intent.putExtra("state", 1);
        sendBroadcast(intent);
    }


    public void pause(View view) {
        /**
         * 发送广播给 服务内的广播接收者
         */
        Intent intent = new Intent("a.b.c.music");
        intent.putExtra("state", 2);
        sendBroadcast(intent);
    }

    public void next(View view) {
        /**
         * 发送广播给 服务内的广播接收者
         */
        Intent intent = new Intent("a.b.c.music");
        intent.putExtra("state", 3);
        sendBroadcast(intent);
    }


    class MusicProgressBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int p = intent.getIntExtra("p", 0);
                sb.setProgress(p);
                tv_show.setText(p + "%");
            }
        }
    }



}
